﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Microsoft.SharePoint;
using Repo.Converters;
using Repo.DataAccess;
using Repo.DataCaching;
using Repo.Filters;
using Repo.Helpers;
using Repo.Interfaces;

namespace Repo
{
    public class Gateway
    {
        public static IEnumerable<T> GetItems<T>() where T : ISharePointItem
        {
            return GetItems<T>(new RepoFilter{ParentList = string.Empty});
        }

        public static IEnumerable<T> GetItems<T>(RepoFilter repoFilter) where T : ISharePointItem
        {
            var key = KeyGenerator.GenerateKey(ContentTypeFinder.GetContentTypeFromType(typeof(T)).Name, null);
            var cachedItems = CacheChecker.CheckForCachedItems(typeof(T), key);
            if (cachedItems == null)
            {
                LoggingHelper.DebugLog("Getting new items for key " + key);
                cachedItems = CacheBuilder.BuildCacheForType(repoFilter.Site, typeof(T));
            }
            if (string.IsNullOrEmpty(repoFilter.ParentList))
            {
                return cachedItems.Cast<T>().Where(x => x.ParentList.Equals(repoFilter.ParentList));
            }
            return cachedItems.Cast<T>();
        }
    }
}
